//
//  NSDate+Calculate.m
//  UtoPassenger
//
//  Created by peter on 15/7/23.
//  Copyright (c) 2015年 maseinfo. All rights reserved.
//

#import "NSDate+Calculate.h"
#import <objc/runtime.h>

static NSCalendar *calendar = nil;
static NSDateComponents *components = nil;

@implementation NSDate (Calculate)

- (NSCalendar *)calendar {
    if(calendar == nil) {
        calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
        calendar.firstWeekday = 2;
    }
    return calendar;
}

- (NSDateComponents *)components {
    if(components == nil) {
        components = [self.calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|kCFCalendarUnitHour|kCFCalendarUnitMinute|kCFCalendarUnitSecond|kCFCalendarUnitWeekOfYear|kCFCalendarUnitWeekday|kCFCalendarUnitWeekdayOrdinal fromDate:self];
    }
    return components;
}

- (DateCircle)currentMonth {
    components = nil;
    self.components.day = 1;
    self.components.hour = 0;
    self.components.minute = 0;
    self.components.second = 0;
    NSDate *beginDate = [self.calendar dateFromComponents:self.components];
    self.components.month+=1;
    NSDate *endDate = [self.calendar dateFromComponents:self.components];
    return (DateCircle){beginDate,endDate};
}

- (DateCircle)currentWeek {
    components = nil;
    NSUInteger adjustedWeekdayOrdinal = [self.calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth | NSCalendarUnitWeekOfYear forDate:self];
    int offsetLeft = (int)adjustedWeekdayOrdinal - 1;
    self.components.hour = 0;
    self.components.minute = 0;
    self.components.second = 0;
    self.components.day -= offsetLeft;
    NSDate *beginDate = [self.calendar dateFromComponents:self.components];
    self.components.day += 7;
    NSDate *endDate = [self.calendar dateFromComponents:self.components];
    return (DateCircle){beginDate,endDate};
}

- (int)week {
    NSUInteger adjustedWeekdayOrdinal = [self.calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth | NSCalendarUnitWeekOfYear forDate:self];
    return (int)adjustedWeekdayOrdinal;
}

- (NSDate *)lastNearestDate {
    return [NSDate dateWithTimeIntervalSince1970:[self timeIntervalSince1970] - 1];
}

- (NSDate *)futureNearestDate {
    return [NSDate dateWithTimeIntervalSince1970:[self timeIntervalSince1970] + 1];
}

@end
